package com.maben.security.util;

import com.maben.security.pojo.UserPO;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * security的用户封装类
 */
@Data
public class CustomUserDetails implements UserDetails {
    private final UserPO userPO; // 封装原始用户信息

    // 构造器
    public CustomUserDetails(UserPO userPO) {
        this.userPO = userPO;
    }


    // 实现 UserDetails 接口的必要方法（直接委托给 userPO）
    @Override
    public String getUsername() {
        return userPO.getUsername();
    }

    @Override
    public String getPassword() {
        return userPO.getPassword();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 之前的权限处理逻辑（角色+权限）
        List<String> allAuthorities = new ArrayList<>();
        if (userPO.getPermissions() != null) {
            allAuthorities.addAll(userPO.getPermissions());
        }
        //  "roles": ["ROLE_USER"] ，必须带前缀【ROLE_】
        if (userPO.getRoles() != null) {
            allAuthorities.addAll(userPO.getRoles());
        }
        return allAuthorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    // 账户是否过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 账户是否锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 密码是否过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 账户是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}